package org.scrm.component;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.scrm.model.SmsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ChannelService implements IChannel {




    @Autowired
    private SendUtil sendUtil;

    /**
     * 企业号
     */
    protected String spCode = "247808";

    /**
     * 用户名
     */
    protected String loginName = "nj_xmzjd";

    /**
     * 密码
     */
    protected String password = "Crm!crm4321";

    private static final String SUCCESS_CODE = "0";


    public SmsResult single(String mobile, String content, String serialNumber) {
        return handleResult(sendUtil.send(spCode, loginName, password, mobile, content, serialNumber));
    }

    public SmsResult multipleSameContent(List<String> mobiles, String content, String serialNumber) {
        return handleResult(sendUtil.send(spCode, loginName, password, String.join(",", mobiles), content, serialNumber));
    }

/*    public SmsResult multipleDiffContent(List<SmsMessageVo> params, String serialNumber) {
        SmsResult finalResult = new SmsResult();
        Map<Integer, String> map = new HashMap<>(100);
        for(SmsMessageVo smsMessageVo : params) {
            String result = sendUtil.send(spCode, loginName, password, smsMessageVo.getMobile(), smsMessageVo.getContent(), serialNumber);
            SmsResult smsResult = handleResult(result);
            if (!SUCCESS_CODE.equals(smsResult.getResult())) {
                map.put(smsMessageVo.getId(), smsResult.getDescription());
            }
        }
        finalResult.setDiffMessageFailResult(map);
        return finalResult;
    }*/

    /**
     * 处理发送结果
     * @param result 发送结果字符串
     * @return 发送结果
     */
    private static SmsResult handleResult(String result) {
        SmsResult smsResult = new SmsResult();
        if (StringUtils.isNotEmpty(result)) {
            String[] strings = result.split("&");
            for (String str : strings) {
                String[] strings1 = str.split("=");
                switch (strings1[0]) {
                    case "result":
                        smsResult.setResult(strings1[1]);
                        break;
                    case "description":
                        smsResult.setDescription(strings1[1]);
                        break;
                    case "faillist":
                        if (strings1.length > 1) {
                            smsResult.setFailList(Arrays.asList(strings1[1].split(",")));
                        }
                        break;
                    default:
                        log.info("不需要解析字段：{}", strings1[0]);
                }
            }
        }
        return smsResult;
    }
}
